package com.sl.ms.trade.handler.alipay;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.sl.ms.trade.annotation.PayChannel;
import com.sl.ms.trade.entity.TradingEntity;
import com.sl.ms.trade.enums.PayChannelEnum;
import com.sl.ms.trade.enums.TradingEnum;
import com.sl.ms.trade.enums.TradingStateEnum;
import com.sl.ms.trade.handler.NativePayHandler;
import com.sl.transport.common.exception.SLException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author wjh
 * @create 2023-09-22 15:12
 */
@Component("aliNativePayHandler")
@Slf4j
@PayChannel(type = PayChannelEnum.ALI_PAY)
public class AliNativePayHandler implements NativePayHandler {
    @Override
    public void createDownLineTrading(TradingEntity tradingEntity) throws SLException {
        //查询配置
        Config config = AlipayConfig.getConfig(tradingEntity.getEnterpriseId());
        //Factory使用配置
        Factory.setOptions(config);
        //调用支付宝API面对面支付
        AlipayTradePrecreateResponse response;
        try {
            response = Factory.Payment.FaceToFace().preCreate(tradingEntity.getMemo(),
                    Convert.toStr(tradingEntity.getTradingOrderNo()),
                    Convert.toStr(tradingEntity.getTradingAmount()));
        } catch (Exception e) {
            throw new SLException(TradingEnum.NATIVE_PAY_FAIL, e);
        }
        //受理结果【只表示请求是否成功，而不是支付是否成功】
        boolean success = ResponseChecker.success(response);
        if (success) {
            String subCode = response.getSubCode();
            String subMsg = response.getQrCode();
            tradingEntity.setPlaceOrderCode(subCode);
            tradingEntity.setPlaceOrderMsg(subMsg);
            tradingEntity.setPlaceOrderJson(JSONUtil.toJsonStr(response));
            tradingEntity.setTradingState(TradingStateEnum.FKZ);
            return;
        }
        throw new SLException(JSONUtil.toJsonStr(response),TradingEnum.NATIVE_PAY_FAIL.getCode(),TradingEnum.NATIVE_PAY_FAIL.getStatus());

    }
}
